package com.wehealth;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import u.aly.ac;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.umeng.analytics.MobclickAgent;
import com.wehealth.Plan_Day;
import com.wehealth.ConsultationQestion.DepartListOnItemClickListener;
import com.wehealth.adapter.DrListAdapter;
import com.wehealth.dm.User;
import com.wehealth.parse.ParseJson;
import com.wehealth.util.DataManger;
import com.wehealth.util.DoTask;

public class Plan_Week extends Fragment {
	
	//SIMMON_ADD
	private MainActivity activity;
	private static  String JSONResult;
	private int[] mProgress = new int[7];
	private ProgressBar[] bGoWeek = new ProgressBar[7];
	private TextView[] mProgressValue = new TextView[7];
	private User user;
	private TextView  planName;
	private Button setPlanID;
	private String[] mPlans ;
	private String mPlanId;
	private SelectPlanDialog selectPlanDialog;
	private DataManger  mDataManger;

	public  Plan_Week()
	{
		Log.i("init:", "plan_week"); 
	}
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		return  inflater.inflate(R.layout.plan_week, null);
	}
	
	
	
	public void onActivityCreated(Bundle savedInstanceState){
		
		super.onActivityCreated(savedInstanceState);
		
		
		 activity = (MainActivity)getActivity();
		 user = activity.getUserInfo();
		 mDataManger = activity.getDataManger();
		 mPlanId = mDataManger.getRecommendID();
		 planName =(TextView)activity.findViewById(R.id.plan_week_recommond_plan_tv);
		 int planid =Integer.valueOf(mPlanId);
		 UpdatePlanNameTextView(planid);	 
		 MobclickAgent.openActivityDurationTrack(false);
		 connectServerForWeekData();
		//返回主页按钮-------------------------------------------------------//
		 Button bBack = (Button) activity.findViewById(R.id.bBack_PlanWeek);
			
		 bBack.setOnClickListener(new View.OnClickListener()
			{
				public void onClick(View v)
				{	
				    activity.switchContentHome();
				}
			});
			
		//------------------------------------------------------------------//
		 
		 
		 
		 bGoWeek[0] = (ProgressBar) activity.findViewById(R.id.pbar_week1);
			
		 bGoWeek[0].setOnClickListener(new View.OnClickListener()
			{
				public void onClick(View v)
				{
					
					Plan_Day planDay = new Plan_Day(1);
					
					if (getActivity() instanceof MainActivity)
					{
						MainActivity activity = (MainActivity) getActivity();
						
						activity.switchContent(planDay);
					}
					
				}
			});
		 
		 
		 bGoWeek[1] = (ProgressBar) activity.findViewById(R.id.pbar_week2);
			
		 bGoWeek[1].setOnClickListener(new View.OnClickListener()
			{
				public void onClick(View v)
				{
					
					Plan_Day planDay = new Plan_Day(2);
					
					if (getActivity() instanceof MainActivity)
					{
						MainActivity activity = (MainActivity) getActivity();
						
						activity.switchContent(planDay);
					}
					
				}
			});
		 
		 
		 bGoWeek[2]= (ProgressBar) activity.findViewById(R.id.pbar_week3);
			
		 bGoWeek[2].setOnClickListener(new View.OnClickListener()
			{
				public void onClick(View v)
				{
					
					Plan_Day planDay = new Plan_Day(3);
					
					if (getActivity() instanceof MainActivity)
					{
						MainActivity activity = (MainActivity) getActivity();
						
						activity.switchContent(planDay);
					}
					
				}
			});
		 
		 bGoWeek[3] = (ProgressBar) activity.findViewById(R.id.pbar_week4);
			
		 bGoWeek[3].setOnClickListener(new View.OnClickListener()
			{
				public void onClick(View v)
				{
					
					Plan_Day planDay = new Plan_Day(4);
					
					if (getActivity() instanceof MainActivity)
					{
						MainActivity activity = (MainActivity) getActivity();
						
						activity.switchContent(planDay);
					}
					
				}
			});
		 
		 bGoWeek[4] = (ProgressBar) activity.findViewById(R.id.pbar_week5);
			
		 bGoWeek[4].setOnClickListener(new View.OnClickListener()
			{
				public void onClick(View v)
				{
					
					Plan_Day planDay = new Plan_Day(5);
					
					if (getActivity() instanceof MainActivity)
					{
						MainActivity activity = (MainActivity) getActivity();
						
						activity.switchContent(planDay);
					}
					
				}
			});
		 
		 bGoWeek[5] = (ProgressBar) activity.findViewById(R.id.pbar_week6);
			
		 bGoWeek[5].setOnClickListener(new View.OnClickListener()
			{
				public void onClick(View v)
				{
					
					Plan_Day planDay = new Plan_Day(6);
					
					if (getActivity() instanceof MainActivity)
					{
						MainActivity activity = (MainActivity) getActivity();
						
						activity.switchContent(planDay);
					}
					
				}
			});
		 
		 bGoWeek[6] = (ProgressBar) activity.findViewById(R.id.pbar_week7);
			
		 bGoWeek[6].setOnClickListener(new View.OnClickListener()
			{
				public void onClick(View v)
				{
					
					Plan_Day planDay = new Plan_Day(7);
					
					if (getActivity() instanceof MainActivity)
					{
						MainActivity activity = (MainActivity) getActivity();
						
						activity.switchContent(planDay);
					}
					
				}
			});
		 
		 
		 mProgressValue[0] = (TextView)activity.findViewById(R.id.textWeek1);
		 mProgressValue[1] = (TextView)activity.findViewById(R.id.textWeek2);
		 mProgressValue[2] = (TextView)activity.findViewById(R.id.textWeek3);
		 mProgressValue[3] = (TextView)activity.findViewById(R.id.textWeek4);
		 mProgressValue[4] = (TextView)activity.findViewById(R.id.textWeek5);
		 mProgressValue[5] = (TextView)activity.findViewById(R.id.textWeek6);
		 mProgressValue[6] = (TextView)activity.findViewById(R.id.textWeek7);
		 
		mPlans = activity.getResources().getStringArray(R.array.questionnaire_page4_plan_list);
			
		 setPlanID = (Button)activity.findViewById(R.id.plan_week_select_plan);
		 setPlanID.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				connectServierGetPlanIds();
			}
		});
		 

	}
	
	
	
	/**
	 * 渲染界面,显示数据
	 */
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message paramMessage) {
			super.handleMessage(paramMessage);
			if(JSONResult!=null){
				switch (paramMessage.what) {
				case 0:
					BindWeekData(JSONResult);
					break;
				case 1:
					UpdatePlanIdData(JSONResult);
					break;
				case 2:
					UpdatePlanIdSelectList(JSONResult);
					break;
				case 3:
					CreatePlanId(JSONResult);
					break;
				default:
					break;
				}
						JSONResult =null;
			}else{
			  //  activity.openMainActivityDialog(); 
			}
		}
	};
	
	private void connectServerForWeekData(){
		//SIMMON_ADD
		new Thread(){
			@Override
			public void run(){
				try {
					getPlanData();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			Message msg = new Message();
			msg.what=0;
			handler.sendMessage(msg);
			}
	}.start();
	}

	private void BindWeekData(String strJSON){
		try{
				 JSONObject jsonObject = new JSONObject(strJSON);
				  JSONArray  weekData =  new JSONArray( jsonObject.getString("result") ); 
				  
				 String mondayValue = weekData.getJSONObject(0).getString("Monday");
				 String tuesdayValue = weekData.getJSONObject(0).getString("Tuesday");
				 String WednesdayValue = weekData.getJSONObject(0).getString("Wednesday");
				 String ThursdayValue =weekData.getJSONObject(0).getString("Thursday");
				 String FridayValue = weekData.getJSONObject(0).getString("Friday");
				 String SaturdayValue = weekData.getJSONObject(0).getString("Saturday");
				 String SundayValue = weekData.getJSONObject(0).getString("Sunday");

				 mProgress[0] =Integer.parseInt(mondayValue);
				 mProgress[1] =Integer.parseInt(tuesdayValue);
				 mProgress[2] =Integer.parseInt(WednesdayValue);
				 mProgress[3] =Integer.parseInt(ThursdayValue);
				 mProgress[4] =Integer.parseInt(FridayValue);
				 mProgress[5] =Integer.parseInt(SaturdayValue);
				 mProgress[6] =Integer.parseInt(SundayValue);
				 
				 for(int i =0; i < 7; i++){
					 bGoWeek[i].setProgress(mProgress[i]);
					 String value =mProgress[i]+"%";
					 mProgressValue[i].setText(value);
				 }
				 			  
    }
    catch(JSONException ex)
    {
    		Log.e("JSON Error: ", ex.toString()); 
    }
		
	}
	
	
	private void  getPlanData() throws IOException
	{
		Log.d("SIMMON","user="+user);
		String userID =String.valueOf(user.getUserId());
		String recommendID = mPlanId;
	
		String httpUrl = com.wehealth.util.GetUrl.Plan_GetHealthSum();
		 HttpPost httpRequest= new HttpPost(httpUrl);
		 
		 List <NameValuePair> params = new ArrayList <NameValuePair>();
		 
		 params.add(new BasicNameValuePair("userID",userID));
		 params.add(new BasicNameValuePair("recommendID",recommendID)); 
		 try
		 {
			 httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );
			
			 HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
			 
			 if(httpResponse.getStatusLine().getStatusCode() == 200)
			 {
				 JSONResult = EntityUtils.toString(httpResponse.getEntity());
				 Log.d("SIMMON","JSONResult ="+JSONResult);
			 }
		 }
		 catch(Exception e)
		 {
			
			 Log.e("error:",  e.toString());
			 
		 }

	}
	
	
    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        MobclickAgent.onPageEnd("Plan_Week"); 
    }


    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        MobclickAgent.onPageStart("Plan_Week"); 
    }
	
	
    private void UpdatePlanNameTextView(int planId){
    	
    	String plantitle =null;
    	switch (planId) {
			case 1:
				plantitle = getString(R.string.questionaire_page4_recommend_project1);
				break;
			case 2:
				plantitle = getString(R.string.questionaire_page4_recommend_project2);
				break;
			case 3:
				plantitle = getString(R.string.questionaire_page4_recommend_project3);
				break;
			case 4:
				plantitle = getString(R.string.questionaire_page4_recommend_project4);
				break;
			case 5:
				plantitle = getString(R.string.questionaire_page4_recommend_project5);
				break;
	
			default:
				break;
		}
    	
    	planName.setText(plantitle);
    }
	
	private void openSelectDepartDialog(){
		MainActivity context = (MainActivity)getActivity();
		PlansListOnItemClickListener  selectPlansOnItemClickListener = new PlansListOnItemClickListener();
		 selectPlanDialog = new SelectPlanDialog(context,R.style.selectDepartDialog,
				 selectPlansOnItemClickListener,mPlans);
		 selectPlanDialog.show();
	}
	
	class PlansListOnItemClickListener implements OnItemClickListener{

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int index,
				long pos2) {
			// TODO Auto-generated method stub
		//	UpdatePlanNameTextView(index+1);
			int planIndex =index+1;
			mPlanId = String.valueOf(planIndex);
			connectServierUpdatePlanId();
			selectPlanDialog.dismiss();
		}
		
	}
	
	
	private void connectServierUpdatePlanId(){
		
		new Thread(){
			@Override
			public void run(){
				try {
					UpdatePlanId();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			Message msg = new Message();
			msg.what =1;
			handler.sendMessage(msg);
			}
		}.start();
	}
	
	private void  UpdatePlanId() throws IOException
	{

		String httpUrl = com.wehealth.util.GetUrl.User_UpdateMyPlan_URL();
		 HttpPost httpRequest= new HttpPost(httpUrl);
		 
		 List <NameValuePair> params = new ArrayList <NameValuePair>();
		 String userId = String.valueOf(user.getUserId());
		 params.add(new BasicNameValuePair("userID",userId));
		 params.add(new BasicNameValuePair("planID",mPlanId));
		 try
		 {
			 httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );
			
			 HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
			 
			 if(httpResponse.getStatusLine().getStatusCode() == 200)
			 {
				 JSONResult = EntityUtils.toString(httpResponse.getEntity());
				 Log.d("SIMMON","########Plan_Day  JSONResult="+JSONResult);
			 }
		 }
		 catch(Exception e)
		 {
			
			 Log.e("error:",  e.toString());
			 
		 }

	}
	
	
	private void connectServierGetPlanIds(){
		
		new Thread(){
			@Override
			public void run(){
				try {
					GetPlanIdsFromNet();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			Message msg = new Message();
			msg.what =2;
			handler.sendMessage(msg);
			}
		}.start();
	}
	
	   private void UpdatePlanIdSelectList(String strJSON){
	       try{
	                JSONObject jsonObject = new JSONObject(strJSON); 
	                JSONArray  aNews =  new JSONArray( jsonObject.getString("result") );  
	                for(int i=0; i<aNews.length(); i++){
	                	mPlans[i]=aNews.getJSONObject(i).getString("name");
	                }
	                
	                openSelectDepartDialog();
	                
	            }
	            catch(JSONException ex)
	            {
	                    Log.e("JSON Error: ", ex.toString()); 
	            }
	    }
	
	   
	   private void  GetPlanIdsFromNet() throws IOException
		{

			String httpUrl = com.wehealth.util.GetUrl.Plan_GetRecommend_URL();
			 HttpPost httpRequest= new HttpPost(httpUrl);

			 try
			 {
				 HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
				 
				 if(httpResponse.getStatusLine().getStatusCode() == 200)
				 {
					 JSONResult = EntityUtils.toString(httpResponse.getEntity());
					 Log.d("SIMMON","Plan_Day  JSONResult="+JSONResult);
				 }
			 }
			 catch(Exception e)
			 {
				
				 Log.e("error:",  e.toString());
				 
			 }

		}
		
		
		   private void UpdatePlanIdData(String strJSON){
		       try{
		                JSONObject jsonObject = new JSONObject(strJSON); 
		                String  result =   jsonObject.getString("result");
		               if(result.equals("1")){
		            	    mDataManger.setRecommendID(mPlanId);
		            	    int plan = Integer.valueOf(mPlanId);
		            	    UpdatePlanNameTextView(plan);
		            	    connectServierCreatePlanId();
		               }else{
		            	   activity.openDialogBt(-100); 
		               }
		            }
		            catch(JSONException ex)
		            {
		                    Log.e("JSON Error: ", ex.toString()); 
		            }
		    }
		
	   
			private void connectServierCreatePlanId(){
				
				new Thread(){
					@Override
					public void run(){
						try {
							Plan_CreateUserPlan();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					Message msg = new Message();
					msg.what =3;
					handler.sendMessage(msg);
					}
				}.start();
			}
		   

			private void  Plan_CreateUserPlan() throws IOException
			{

				String httpUrl = com.wehealth.util.GetUrl.Plan_CreateUserPlan_URL();
				 HttpPost httpRequest= new HttpPost(httpUrl);
				 
				 List <NameValuePair> params = new ArrayList <NameValuePair>();
				 String userId = String.valueOf(user.getUserId());
				 params.add(new BasicNameValuePair("userID",userId));
				 params.add(new BasicNameValuePair("recommendID",mPlanId));
				 try
				 {
					 httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );
					
					 HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
					 
					 if(httpResponse.getStatusLine().getStatusCode() == 200)
					 {
						 JSONResult = EntityUtils.toString(httpResponse.getEntity());
						 Log.d("SIMMON","###!!!!!!!Plan_Day  JSONResult="+JSONResult);
					 }
				 }
				 catch(Exception e)
				 {
					
					 Log.e("error:",  e.toString());
					 
				 }

			}
			
			   private void CreatePlanId(String strJSON){
			       try{
			
			                JSONObject jsonObject = new JSONObject(strJSON); 
			                String  result =   jsonObject.getString("result");
			               if(result.equals("1")){
			            	    mDataManger.setRecommendID(mPlanId);
			            	    int plan = Integer.valueOf(mPlanId);
			            	    UpdatePlanNameTextView(plan);
			            	    connectServerForWeekData();
			             	   Log.d("SIMMON","###!!!!!!!Plan_Day  CreatePlanId");
			               }else{
			            	   activity.openDialogBt(-100); 
			               }
			            }
			            catch(JSONException ex)
			            {
			                    Log.e("JSON Error: ", ex.toString()); 
			            }
			    }
			
	
}
